<template>
  <div class="loan-apply">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷款申请</h3>
        </div>
      </template>

      <!-- 申请表单 -->
      <el-form
        ref="applyFormRef"
        :model="applyForm"
        :rules="rules"
        label-width="120px"
        class="apply-form"
        v-loading="loading"
      >
        <!-- 客户信息 -->
        <el-divider>客户信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="applyForm.customerName"
                placeholder="请输入客户名称"
                style="width: 100%"
                @change="generateCustomerId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户ID" prop="customerId">
              <el-input v-model="applyForm.customerId" placeholder="系统自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="applyForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 贷款信息 -->
        <el-divider>贷款信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款类型" prop="loanType">
              <el-select v-model="applyForm.loanType" placeholder="请选择贷款类型" style="width: 100%">
                <el-option label="个人消费贷" value="personal" />
                <el-option label="住房贷款" value="house" />
                <el-option label="车辆贷款" value="car" />
                <el-option label="经营贷款" value="business" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款金额" prop="amount">
              <el-input-number
                v-model="applyForm.amount"
                :min="1000"
                :max="1000000"
                :step="1000"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款期限" prop="term">
              <el-select v-model="applyForm.term" placeholder="请选择贷款期限" style="width: 100%">
                <el-option label="3个月" :value="3" />
                <el-option label="6个月" :value="6" />
                <el-option label="12个月" :value="12" />
                <el-option label="24个月" :value="24" />
                <el-option label="36个月" :value="36" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款用途" prop="purpose">
              <el-select v-model="applyForm.purpose" placeholder="请选择贷款用途" style="width: 100%">
                <el-option label="经营周转" value="business" />
                <el-option label="设备采购" value="equipment" />
                <el-option label="技术改造" value="technology" />
                <el-option label="其他用途" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="还款方式" prop="repaymentMethod">
              <el-select v-model="applyForm.repaymentMethod" placeholder="请选择还款方式" style="width: 100%">
                <el-option label="等额本息" value="equalInstallment" />
                <el-option label="等额本金" value="equalPrincipal" />
                <el-option label="先息后本" value="interestFirst" />
                <el-option label="一次性还本付息" value="bulletPayment" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="担保方式" prop="guaranteeType">
              <el-select 
                v-model="applyForm.guaranteeType" 
                placeholder="请选择担保方式" 
                style="width: 100%"
                @change="handleGuaranteeTypeChange"
              >
                <el-option label="信用" value="credit" />
                <el-option label="保证" value="guarantee" />
                <el-option label="抵押" value="mortgage" />
                <el-option label="质押" value="pledge" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="showCollateralValue">
          <el-col :span="12">
            <el-form-item label="担保物价值" prop="collateralValue">
              <el-input-number
                v-model="applyForm.collateralValue"
                :min="0"
                :step="1000"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 附件上传 -->
        <el-divider>附件上传</el-divider>
        <el-form-item label="身份证明" prop="idCard">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadIdCard"
            :file-list="idCardFileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="2"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png/pdf格式，大小不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="收入证明" prop="income">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadIncome"
            :file-list="incomeFileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="2"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png/pdf格式，大小不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="抵押物证明" prop="collateral" v-if="showCollateralValue">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadCollateral"
            :file-list="collateralFileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="2"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png/pdf格式，大小不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="其他材料" prop="other">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="uploadOther"
            :file-list="otherFileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="5"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png/pdf格式，大小不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 按钮操作 -->
        <el-form-item>
          <el-button type="primary" @click="submitApply">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loanApplyApi } from '@/api/loan'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const applyFormRef = ref(null)
const loading = ref(false)
const isEdit = ref(false)
const loanId = ref('')

// 文件列表
const idCardFileList = ref([])
const incomeFileList = ref([])
const collateralFileList = ref([])
const otherFileList = ref([])

// 申请表单
const applyForm = reactive({
  customerName: '',
  customerId: '',
  phone: '',
  loanType: '',
  amount: 10000,
  term: 12,
  purpose: '',
  repaymentMethod: 'equalInstallment',
  guaranteeType: 'credit',
  collateralValue: 0
})

// 生成8位随机数字ID
const generateCustomerId = () => {
  if (!applyForm.customerName) return;
  if (!isEdit.value) { // 只有在新增模式下才重新生成ID
    const randomId = Math.floor(10000000 + Math.random() * 90000000);
    applyForm.customerId = randomId.toString();
  }
}

// 计算属性：是否显示担保物价值
const showCollateralValue = computed(() => {
  return applyForm.guaranteeType === 'mortgage' || applyForm.guaranteeType === 'pledge'
})

// 表单验证规则
const rules = {
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '客户ID不能为空', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  loanType: [
    { required: true, message: '请选择贷款类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入贷款金额', trigger: 'blur' }
  ],
  term: [
    { required: true, message: '请选择贷款期限', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请选择贷款用途', trigger: 'change' }
  ],
  repaymentMethod: [
    { required: true, message: '请选择还款方式', trigger: 'change' }
  ],
  guaranteeType: [
    { required: true, message: '请选择担保方式', trigger: 'change' }
  ],
  collateralValue: [
    { 
      required: true, 
      message: '请输入担保物价值', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (showCollateralValue.value && (!value || value <= 0)) {
          callback(new Error('担保物价值必须大于0'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 担保方式变更
const handleGuaranteeTypeChange = (value) => {
  if (value !== 'mortgage' && value !== 'pledge') {
    applyForm.collateralValue = 0
  }
}

// 文件上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isJPG && !isPNG && !isPDF) {
    ElMessage.error('上传文件只能是 JPG/PNG/PDF 格式!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传身份证
const uploadIdCard = async (params) => {
  try {
    if (!loanId.value) {
      ElMessage.warning('请先保存贷款申请，再上传附件')
      return
    }
    
    const formData = new FormData()
    formData.append('applyId', loanId.value)
    formData.append('fileType', 'idCard')
    formData.append('file', params.file)
    
    const res = await loanApplyApi.uploadFile(formData)
    if (res.code === 200) {
      ElMessage.success('文件上传成功')
      idCardFileList.value.push({
        name: params.file.name,
        url: res.data.fileUrl
      })
    } else {
      ElMessage.error(res.message || '文件上传失败')
    }
  } catch (error) {
    console.error('上传文件出错:', error)
    ElMessage.error('文件上传失败')
  }
}

// 上传收入证明
const uploadIncome = async (params) => {
  try {
    if (!loanId.value) {
      ElMessage.warning('请先保存贷款申请，再上传附件')
      return
    }
    
    const formData = new FormData()
    formData.append('applyId', loanId.value)
    formData.append('fileType', 'income')
    formData.append('file', params.file)
    
    const res = await loanApplyApi.uploadFile(formData)
    if (res.code === 200) {
      ElMessage.success('文件上传成功')
      incomeFileList.value.push({
        name: params.file.name,
        url: res.data.fileUrl
      })
    } else {
      ElMessage.error(res.message || '文件上传失败')
    }
  } catch (error) {
    console.error('上传文件出错:', error)
    ElMessage.error('文件上传失败')
  }
}

// 上传抵押物证明
const uploadCollateral = async (params) => {
  try {
    if (!loanId.value) {
      ElMessage.warning('请先保存贷款申请，再上传附件')
      return
    }
    
    const formData = new FormData()
    formData.append('applyId', loanId.value)
    formData.append('fileType', 'collateral')
    formData.append('file', params.file)
    
    const res = await loanApplyApi.uploadFile(formData)
    if (res.code === 200) {
      ElMessage.success('文件上传成功')
      collateralFileList.value.push({
        name: params.file.name,
        url: res.data.fileUrl
      })
    } else {
      ElMessage.error(res.message || '文件上传失败')
    }
  } catch (error) {
    console.error('上传文件出错:', error)
    ElMessage.error('文件上传失败')
  }
}

// 上传其他资料
const uploadOther = async (params) => {
  try {
    if (!loanId.value) {
      ElMessage.warning('请先保存贷款申请，再上传附件')
      return
    }
    
    const formData = new FormData()
    formData.append('applyId', loanId.value)
    formData.append('fileType', 'other')
    formData.append('file', params.file)
    
    const res = await loanApplyApi.uploadFile(formData)
    if (res.code === 200) {
      ElMessage.success('文件上传成功')
      otherFileList.value.push({
        name: params.file.name,
        url: res.data.fileUrl
      })
    } else {
      ElMessage.error(res.message || '文件上传失败')
    }
  } catch (error) {
    console.error('上传文件出错:', error)
    ElMessage.error('文件上传失败')
  }
}

// 文件删除
const handleRemove = (file, fileList) => {
  // 这里可以调用接口删除已上传的文件
  console.log('删除文件:', file)
}

// 超出上传限制
const handleExceed = (files) => {
  ElMessage.warning(`超出上传限制，一次最多上传 ${files.length} 个文件`)
}

// 获取贷款详情
const getLoanDetail = async (id) => {
  try {
    loading.value = true
    const res = await loanApplyApi.getInfo(id)
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构
      let data = null
      
      if (res.data && typeof res.data === 'object' && !Array.isArray(res.data)) {
        // 直接是对象结构
        data = res.data
      } else if (res.data && res.data.data && typeof res.data.data === 'object') {
        // 嵌套结构
        data = res.data.data
      } else {
        console.warn('未识别的贷款详情数据结构:', res)
        ElMessage.error('获取贷款详情数据格式异常')
        return
      }
      
      // 填充表单数据
      Object.keys(applyForm).forEach(key => {
        if (data[key] !== undefined) {
          applyForm[key] = data[key]
        }
      })
      
      // 如果有特殊处理的字段
      if (data.loanAmount) applyForm.amount = data.loanAmount
      if (data.loanTerm) applyForm.term = data.loanTerm
      
      // 处理附件
      if (data.attachments && data.attachments.length > 0) {
        data.attachments.forEach(file => {
          const fileItem = {
            name: file.fileName,
            url: file.fileUrl
          }
          
          if (file.fileType === 'idCard') {
            idCardFileList.value.push(fileItem)
          } else if (file.fileType === 'income') {
            incomeFileList.value.push(fileItem)
          } else if (file.fileType === 'collateral') {
            collateralFileList.value.push(fileItem)
          } else if (file.fileType === 'other') {
            otherFileList.value.push(fileItem)
          }
        })
      }
      
      loanId.value = id
    } else {
      ElMessage.error(res.msg || res.message || '获取贷款详情失败')
    }
  } catch (error) {
    console.error('获取贷款详情出错:', error)
    ElMessage.error('获取贷款详情失败')
  } finally {
    loading.value = false
  }
}

// 提交贷款申请
const submitApply = async () => {
  if (!applyFormRef.value) return
  
  await applyFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true
        
        const data = { ...applyForm }
        
        // 转换数值类型
        data.amount = Number(data.amount)
        data.term = Number(data.term)
        data.collateralValue = Number(data.collateralValue)
        
        let res
        
        if (isEdit.value) {
          // 编辑模式
          data.id = loanId.value
          res = await loanApplyApi.update(data)
        } else {
          // 新增模式
          res = await loanApplyApi.add(data)
        }
        
        if (res.code === 200 || res.code === '200') {
          ElMessage.success(isEdit.value ? '贷款申请修改成功' : '贷款申请提交成功')
          
          if (!isEdit.value) {
            // 新增成功后，设置为编辑模式，并获取ID
            isEdit.value = true
            
            // 处理可能的嵌套数据结构
            if (res.data && res.data.id) {
              loanId.value = res.data.id
            } else if (res.data && res.data.data && res.data.data.id) {
              loanId.value = res.data.data.id
            } else {
              console.warn('未识别的贷款申请返回结构:', res)
            }
            
            ElMessageBox.confirm(
              '贷款申请已保存，是否继续上传附件？',
              '提示',
              {
                confirmButtonText: '继续完善',
                cancelButtonText: '返回列表',
                type: 'info',
              }
            ).then(() => {
              // 继续完善
            }).catch(() => {
              // 返回列表
              goBack()
            })
          } else {
            // 修改成功后询问是否返回
            ElMessageBox.confirm(
              '贷款申请已修改，是否返回列表？',
              '提示',
              {
                confirmButtonText: '返回列表',
                cancelButtonText: '继续编辑',
                type: 'info',
              }
            ).then(() => {
              goBack()
            }).catch(() => {
              // 继续编辑
            })
          }
        } else {
          ElMessage.error(res.msg || res.message || '操作失败')
        }
      } catch (error) {
        console.error('提交贷款申请出错:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('请完善表单信息')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (applyFormRef.value) {
    applyFormRef.value.resetFields()
  }
  
  // 重置文件列表
  idCardFileList.value = []
  incomeFileList.value = []
  collateralFileList.value = []
  otherFileList.value = []
  
  // 如果是编辑模式，重新加载数据
  if (isEdit.value && loanId.value) {
    getLoanDetail(loanId.value)
  }
}

// 返回
const goBack = () => {
  router.push('/loan/list')
}

onMounted(() => {
  // 检查是否是编辑模式
  const id = route.query.id
  if (id) {
    isEdit.value = true
    loanId.value = id
    getLoanDetail(id)
  } else {
    // 新增模式下生成随机客户ID
    generateCustomerId()
  }
})
</script>

<style scoped>
.loan-apply {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.apply-form {
  padding: 20px 0;
}

.el-divider {
  margin: 24px 0;
}

.upload-demo {
  margin: 10px 0;
}
</style> 